<?php
namespace App\Common;

use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Db\Connection\Connection;
use Swoft\Db\Contract\DbSelectorInterface;
use Swoft\Db\Exception\DbException;
use Swoft\Console\ConsoleContext;
use Swoft\Rpc\Server\ServiceContext;

/**
 * Class DbSelector
 * @package App\Common
 * @Bean()
 */
class DbSelector implements DbSelectorInterface
{

    /**
     * @param Connection $connection
     */
    public function select(Connection $connection): void
    {
        //默认取到Jiujiu
        if(context() instanceof  ConsoleContext){
            $tenant = "jiujiu";
        }elseif(context() instanceof ServiceContext){
            $tenant = context()->getRequest()->getParams();
            $tenant = isset($tenant['tenant'])?$tenant['tenant']:'Jiujiu';
        }else{
            // 获取 tenant 租户
            $tenant = getTenant();
        }

        $dbConfig = config(strtolower($tenant), []);
        $dbName = $dbConfig['dbName'] ?? '';

        //add tenant limit
        if(strtolower($tenant) == 'admin'){
            $result = true;
        }else{
            $result = $connection->db(env('APP_ENV', 'local').'_gateway_admin')->select('select * from tenant where prefix = "'.strtolower($tenant).'"');
        }

        if(!$result){
            $defaultDb = $connection->getDb();
            $connection->db($defaultDb);
        }else{
            // 优先使用配置文件中的 dbName
            if (!empty($dbName)) {
                $connection->db($dbName);
            } else {
                $defaultDb = $connection->getDb();
                $dbName = env('APP_ENV')."_".$defaultDb."_".$tenant;
                $connection->db($dbName);
            }
        }
    }
}
